package com.gmail.bogatyr.alexander.service;

import com.gmail.bogatyr.alexander.dao.BaseDao;
import com.gmail.bogatyr.alexander.entity.BaseEntity;
import org.hibernate.Session;

import java.io.Serializable;
import java.util.Collection;

/**
 * This class represents...
 */
public abstract class BaseService<T extends BaseEntity, V extends Serializable, W extends BaseDao> {

    //TODO use isWasCommit

    private W clazz;

    public BaseService(final W clazz) {
        this.clazz = clazz;
    }

    protected Session getSession() {
        return clazz.getSession();
    }

    public T findById(final V id) {
//        Transaction tx = getSession().getTransaction();
//        tx.begin();
        T result = (T) clazz.findById(id);
//        tx.commit();
//        return tx.wasCommitted() ? result : null;
        return result;
    }

    public Collection<T> findAll() {
//        getSession().beginTransaction();
        Collection<T> result = clazz.findAll();
//        getSession().getTransaction().commit();
        return result;
    }

    public V save(final T entity) {
//        Transaction tx = getSession().getTransaction();
//        tx.begin();
        Serializable result = clazz.save((Serializable) entity);
//        tx.commit();
//        return tx.wasCommitted() ? (V) result : null;
        return (V) result;
    }

    public T update(final T entity) {
        getSession().beginTransaction();
        T result = (T) clazz.update((Serializable) entity);
        getSession().getTransaction().commit();
        return result;
    }

    public void delete(final T entity) {
        getSession().beginTransaction();
        clazz.delete((Serializable) entity);
        getSession().getTransaction().commit();
    }

    public void deleteById(final V id) {
        getSession().beginTransaction();
        clazz.deleteById(id);
        getSession().getTransaction().commit();
    }
}
